﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using AForge.Video;
using AForge.Video.DirectShow;
using System.Drawing;
using project1113;
using project1113.SomeTools;
using project1113.Wrold;

namespace PRJ1113.Camera
{ 
    public class Camera:IDeviceUpdate
    {
        
        private static Camera? myCamera = null;
        private VideoCaptureDevice videoSource;
        private Bitmap? _metaBitmap;
        public Bitmap? OutputBitmap { get; private set;}
        public static Camera? OnlyInstance
        {
            get
            {
                if (myCamera is null)
                {
                    myCamera = new Camera();
                }
                return myCamera;
            }
        }
        public Camera()
        {
            // 初始化摄像头
            FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (videoDevices.Count > 0)
            {
                videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
                videoSource.NewFrame += VideoSource_NewFrame;
                videoSource.Start();
                StaticLogWrite.Logger.Log(LogLevel.Info, "摄像头开启成功");
            }
            else
            {
                StaticLogWrite.Logger.Log(LogLevel.Error,"没有检测到摄像头");
                throw new InvalidOperationException("No video devices found.");
            }
        }

        public void Update()
        {
            lock (WorldModel.CurrentWorld.lockObject)
            {
                OutputBitmap = _metaBitmap;
                _metaBitmap = null;
            }

        }
        private void VideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            // 处理新的帧，这里简单地将其保存为 Bitmap
            lock (WorldModel.CurrentWorld.lockObject)
            {
                _metaBitmap = (Bitmap)eventArgs.Frame.Clone();
            }
        }
    }

}
